# -*- coding: utf-8 -*-
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "e家保家庭共享健康保障计划"

    # 生产产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 社保
                "socialSec": ["Y", "N"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 重大疾病保险金
                "majorDisease": ["100000"],
                # 一般医疗保险金
                "generalMedic": ["3000000"],
                # 恶性肿瘤保险金
                "seriousCancer": ["3000000"],
                # 投保对象
                "payObject": ["子女"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 66)],
                # 性别
                "gender": ["M", "F"],
                # 社保
                "socialSec": ["Y", "N"],
                # 保障期限
                "expire": ["1年"],
                # 交费类型
                "payType": ["年交"],
                # 重大疾病保险金
                "majorDisease": ["100000"],
                # 一般医疗保险金
                "generalMedic": ["3000000"],
                # 恶性肿瘤保险金
                "seriousCancer": ["3000000"],
                # 投保对象
                "payObject": ["本人/父母/配偶"]
            }

        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["socialSec"], plan[k]["expire"],
                             plan[k]["payType"], plan[k]["majorDisease"], plan[k]["generalMedic"],
                             plan[k]["seriousCancer"], plan[k]["payObject"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8]
                ))

    # 执行爬虫
    def requestJson(self, dt=None):

        if dt["payType"] == "儿女":
            data = {
                "calculateData": {"calstartDate": "2020-02-27 00:00:00", "insuredType": "famliy",
                                  "planId": "1030A00A01",
                                  "insuredNum": 1, "calpayType": "Y", "liabilityContents": [
                        {"liabilityId": "1030001", "amount": "100000", "liabilityName": "重大疾病保险金",
                         "liabilityAmount": "10万"},
                        {"liabilityId": "1030002", "amount": "3000000", "liabilityName": "一般医疗保险金（共享保额）",
                         "liabilityAmount": "300万"},
                        {"liabilityId": "1030003", "amount": "3000000", "liabilityName": "恶性肿瘤医疗保险金（共享保额）",
                         "liabilityAmount": "300万"},
                        {"liabilityId": "1030004", "amount": "0", "liabilityName": "附加被保人保额共享（共享保额）",
                         "liabilityAmount": ""}]}, "insuredData": [
                    {"index": 1, "insuredRelationship": "40", "insuredAge": dt["year"], "insuredGender": "1" if dt["gender"]=="M" else "2" ,
                     "insuredBirth": "2002-02-28", "minimum": "0", "maximum": "65", "planAgeMin": "0",
                     "planAgeMax": "65",
                     "planLiabilityList": [{"liabilityId": "1030001", "amount": "100000", "liabilityName": "重大疾病保险金",
                                            "liabilityAmount": "10万"},
                                           {"liabilityId": "1030002", "amount": "3000000",
                                            "liabilityName": "一般医疗保险金（共享保额）",
                                            "liabilityAmount": "300万"}, {"liabilityId": "1030003", "amount": "3000000",
                                                                         "liabilityName": "恶性肿瘤医疗保险金（共享保额）",
                                                                         "liabilityAmount": "300万"},
                                           {"liabilityId": "1030004", "amount": "0", "liabilityName": "附加被保人保额共享（共享保额）",
                                            "liabilityAmount": ""}], "liabilityContents": [
                        {"liabilityId": "1030001", "amount": "100000", "liabilityName": "重大疾病保险金",
                         "liabilityAmount": "10万"},
                        {"liabilityId": "1030002", "amount": "3000000", "liabilityName": "一般医疗保险金（共享保额）",
                         "liabilityAmount": "300万"},
                        {"liabilityId": "1030003", "amount": "3000000", "liabilityName": "恶性肿瘤医疗保险金（共享保额）",
                         "liabilityAmount": "300万"},
                        {"liabilityId": "1030004", "amount": "0", "liabilityName": "附加被保人保额共享（共享保额）",
                         "liabilityAmount": ""}], "socialSecurity": "1" if dt["socialSec"] == "Y" else "0", "insuredOrder": 1}],
                "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1232511064153915392",
                                 "applicationToken": "73be608e506a2d9d7064aae164b59459",
                                 "workqueueId": "1173412248173264896", "channelId": "3", "platformId": "pc",
                                 "referId": ""},
                "userDefine": {"from": "details"}}
        else:

            data = {"calculateData": {"calstartDate": "2020-02-27 00:00:00", "insuredType": "famliy",
                                      "planId": "1030A00A01", "insuredNum": 1, "calpayType": "Y", "liabilityContents": [
                    {"liabilityId": "1030001", "amount": "100000", "liabilityName": "重大疾病保险金",
                     "liabilityAmount": "10万"},
                    {"liabilityId": "1030002", "amount": "3000000", "liabilityName": "一般医疗保险金（共享保额）",
                     "liabilityAmount": "300万"},
                    {"liabilityId": "1030003", "amount": "3000000", "liabilityName": "恶性肿瘤医疗保险金（共享保额）",
                     "liabilityAmount": "300万"},
                    {"liabilityId": "1030004", "amount": "0", "liabilityName": "附加被保人保额共享（共享保额）",
                     "liabilityAmount": ""}]}, "insuredData": [
                {"index": 1, "insuredRelationship": "50", "insuredAge": dt["year"], "insuredGender": "1" if dt["gender"]=="M" else "2",
                 "insuredBirth": "2000-10-17", "minimum": "0", "maximum": "65", "planAgeMin": "0", "planAgeMax": "65",
                 "planLiabilityList": [{"liabilityId": "1030001", "amount": "100000", "liabilityName": "重大疾病保险金",
                                        "liabilityAmount": "10万"},
                                       {"liabilityId": "1030002", "amount": "3000000", "liabilityName": "一般医疗保险金（共享保额）",
                                        "liabilityAmount": "300万"}, {"liabilityId": "1030003", "amount": "3000000",
                                                                     "liabilityName": "恶性肿瘤医疗保险金（共享保额）",
                                                                     "liabilityAmount": "300万"},
                                       {"liabilityId": "1030004", "amount": "0", "liabilityName": "附加被保人保额共享（共享保额）",
                                        "liabilityAmount": ""}], "liabilityContents": [
                    {"liabilityId": "1030001", "amount": "100000", "liabilityName": "重大疾病保险金",
                     "liabilityAmount": "10万"},
                    {"liabilityId": "1030002", "amount": "3000000", "liabilityName": "一般医疗保险金（共享保额）",
                     "liabilityAmount": "300万"},
                    {"liabilityId": "1030003", "amount": "3000000", "liabilityName": "恶性肿瘤医疗保险金（共享保额）",
                     "liabilityAmount": "300万"},
                    {"liabilityId": "1030004", "amount": "0", "liabilityName": "附加被保人保额共享（共享保额）",
                     "liabilityAmount": ""}], "socialSecurity": "1" if dt["socialSec"] == "Y" else "0" , "insuredOrder": 1}],
                    "exchangeData": {"memberId": "", "memberToken": "", "applicationId": "1232511064153915392",
                                     "applicationToken": "73be608e506a2d9d7064aae164b59459",
                                     "workqueueId": "1173412248173264896", "channelId": "3", "platformId": "pc",
                                     "referId": ""}, "userDefine": {"from": "details"}}

        payload = json.dumps(data)
        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)
        if r.status_code == 200 and "保费试算成功" in r.text:
            price = (Helper.decimalParse(r.json()["data"]["sumPremium"]))
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( self.name )
            print("\n/*产品价格数据更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

